package com.github.cyf.config;

import com.github.vertical_blank.sqlformatter.SqlFormatter;
import com.p6spy.engine.common.P6Util;
import com.p6spy.engine.spy.appender.MessageFormattingStrategy;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author chenyifan
 * @create 2024-03-13 20:48
 */
public class P6SpyLogger implements MessageFormattingStrategy {

    private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 自定义sql日志打印
     *
     * @param connectionId 连接标识
     * @param now          执行时间
     * @param elapsed      执行秒数ms
     * @param category     statement
     * @param prepared     准备sql语句
     * @param sql          sql语句
     * @param s4           数据库url连接
     * @return {@link String}
     */
    @Override
    public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql, String s4) {
        if (!sql.trim().isEmpty()) {
            return   "============== SQL LOGGER BEGIN ==============" + "\r\n" +
                    "SQL 执行时间：" + dateTimeFormatter.format(LocalDateTime.now()) + "\n" +
                    "SQL 执行毫秒：" + elapsed + "ms" + "\n" +
                    "SQL 执行语句：" + "\r\n" + SqlFormatter.format(sql) + "\r\n" +
                    "==============  SQL LOGGER END  ==============";
        }
        return "";
    }
}
